package com.hetwen.search.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap.Config;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.LayoutManager;
import android.support.v7.widget.RecyclerView.OnScrollListener;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.SearchView.OnQueryTextListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import cn.android.common.util.StringUtils;
import cn.android.common.util.ToastUtils;

import com.hetwen.search.R;
import com.hetwen.search.activity.base.BaseActivity;
import com.hetwen.search.http.ResponseHandler;
import com.hetwen.search.log.Logger;
import com.hetwen.search.model.BDImage;
import com.hetwen.search.model.BDImage.Data;
import com.hetwen.search.model.DataManager;
import com.lidroid.xutils.BitmapUtils;
import com.umeng.message.UmengRegistrar;

public class MainActivity extends BaseActivity {
	
	private static final int RN = 10;

	private String keyword;

	private SearchView searchView;
	private RecyclerView recyclerView;

	private List<BDImage.Data> list;

	private RecyclerView.Adapter<ImagesViewHolder> adapter;

	private DataManager manager;
	
	private int pn = 0;

	@Override
	protected void loadView() {
		setContentView(R.layout.activity_main);
	}

	@Override
	protected void initView() {
		recyclerView = (RecyclerView) findViewById(R.id.activity_main_recycler_view);
		recyclerView.setLayoutManager(new LinearLayoutManager(this));
		recyclerView.setItemAnimator(new DefaultItemAnimator());
		recyclerView.setHasFixedSize(true);
	}

	@Override
	protected void initData() {
		manager = DataManager.getInstance(mContext);
		
		String device_token = UmengRegistrar.getRegistrationId(mContext);
		Logger.getInstance().i(mTag, "DeviceToken:" + device_token);
		
		list = new ArrayList<BDImage.Data>();

		adapter = new ImagesAdapter(list);
		recyclerView.setAdapter(adapter);

		final LayoutManager layoutManager = recyclerView.getLayoutManager();
		recyclerView.addOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
				super.onScrolled(recyclerView, dx, dy);
				int last = ((LinearLayoutManager) layoutManager)
						.findLastVisibleItemPosition();
				int total = layoutManager.getItemCount();
				if (last >= total - 1 && dy > 0) {
					// 加载更多
					query(keyword);
				}
			}

		});
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		searchView = (SearchView) menu.findItem(R.id.action_search)
				.getActionView();
		searchView.setOnQueryTextListener(new OnQueryTextListener() {

			@Override
			public boolean onQueryTextSubmit(String keyword) {
				logger.i(mTag, "onQueryTextSubmit:" + keyword);
				query(keyword);
				return true;
			}

			@Override
			public boolean onQueryTextChange(String newText) {
				 logger.i(mTag, "onQueryTextChange:"+newText);
				return true;
			}
		});
		return true;
	}

	private class ImagesAdapter extends RecyclerView.Adapter<ImagesViewHolder> {

		private List<BDImage.Data> list;
		private BitmapUtils bitmapUtils;

		public ImagesAdapter(List<Data> list) {
			this.list = list;
			bitmapUtils = new BitmapUtils(mContext, mContext.getCacheDir()
					.getPath());
			bitmapUtils.configDiskCacheEnabled(true);
			bitmapUtils.configDefaultBitmapConfig(Config.RGB_565);
			bitmapUtils.configDefaultLoadFailedImage(R.drawable.loading);
			bitmapUtils.configDefaultLoadFailedImage(R.drawable.loading);
		}

		@Override
		public int getItemCount() {
			return list.size();
		}

		@Override
		public long getItemId(int position) {
			return super.getItemId(position);
		}

		@Override
		public ImagesViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
			View v = LayoutInflater.from(viewGroup.getContext())
					.inflate(R.layout.activity_main_recycler_view_item,
							viewGroup, false);
			return new ImagesViewHolder(v);
		}

		@Override
		public void onBindViewHolder(ImagesViewHolder holder, int position) {
			holder.tv.setText(keyword + position);
			String url = list.get(position).objURL;
			logger.i(mTag, "url-" + position + ":" + url);
			bitmapUtils.display(holder.iv, url);
		}
	}

	private class ImagesViewHolder extends RecyclerView.ViewHolder implements
			OnClickListener {
		
		public ImageView iv;
		public TextView tv;

		public ImagesViewHolder(View v) {
			super(v);
			iv = (ImageView) v.findViewById(R.id.card_view_item_image);
			tv = (TextView) v.findViewById(R.id.card_view_item_text);
			v.setOnClickListener(this);
		}

		@SuppressWarnings("deprecation")
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(MainActivity.this, ImageActivity.class);
			intent.putExtra("url", list.get(getPosition()).objURL);
			startActivity(intent);
		}
	}

	protected void query(String keyword) {

		if (StringUtils.isBlank(keyword)) {
			return;
		}

		hideInputMethod();
		
		if (!keyword.equals(this.keyword)) {
			this.keyword = keyword;
			pn = 0;
			list.clear();
			adapter.notifyDataSetChanged();
		}
		
		searchImage(keyword);
		
	}
	
	/**
	 * 调用接口搜索图片
	 * @param keyword
	 */
	private void searchImage(String keyword) {
		showLoadingDialog();
		manager.searchImage(keyword, RN, pn, new ResponseHandler(){
			@Override
			public <T> void onSuccess(String response, T t) {
				super.onSuccess(response, t);
				closeLoadingDialog();
				if(t!=null && t instanceof BDImage){
					BDImage bdimage = (BDImage) t;
					bdimage.data.remove(RN);
					list.addAll(bdimage.data);
					adapter.notifyDataSetChanged();
					pn = pn + RN;
				}
			}
			
			@Override
			public void onFailure(String errorcode, String msg) {
				super.onFailure(errorcode, msg);
				closeLoadingDialog();
				ToastUtils.show(mContext, msg);
			}
		});
	}

	/**
	 * 隐藏输入法
	 */
	protected void hideInputMethod() {
		searchView.clearFocus();
	}
}
